import React, {useState,useEffect} from "react";
import {get, map, trim} from "lodash";
import locale from 'antd/es/date-picker/locale/zh_CN';
import DatePicker from "antd/lib/date-picker";
import {UseQueryCusomer} from "@/services/customer";
import {useQueryEnums} from "@/services/enums";
// import Icon from "antd/lib/icon";
// import Button from "antd/lib/button";
import Upload from "antd/lib/upload";
import {Modal, Form,Row,Col, Input, Checkbox, Select, Button,Cascader } from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {UserProfile} from "@/components/proptypes";
import Uploads from "@/services/uploads";
import {UploadOutlined, StarOutlined} from "@ant-design/icons";
import notification from "@/services/notification";
import 'antd/dist/antd.less'

function CreateApplyDialog({ apply_item, dialog }) {
  const {optionsLoaded, options } = useQueryEnums('contract_enum');
  const {customerloaded,customer} = UseQueryCusomer('2');
  const [dataLoaded, setDataLoaded] = useState(apply_item.id ===0 ? true : false);
  const [bill, setbill] = useState("");
  const [employee, setemployee] = useState("");
  const [department, setdepartment] = useState("");
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [type, setType] = useState("");
  const [party_a, setparty_a] = useState("");
  const [party_b, setparty_b] = useState("");
  const [party_c, setparty_c] = useState("");
  const [pay_direction, setpay_direction] = useState("");
  const [sign, setsign] = useState("");
  const [starts, setstarts] = useState("");
  const [ends, setends] = useState("");
  const [start, setstart] = useState("");
  const [message, setMessage] = useState("");
  const [amount, setAmount] = useState("");
  const [amount_words, setamount_words] = useState("");
  const [bytstatus, setbytstatus] = useState(false);
   const [annex, setAnnex] = useState({});
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateApplyEnabled =useState(true);// policy.isAdmin() || policy.isDefault();
  const [typedetail, settypedetail] = useState("");
  const [itemvalue, setitemvalue] = useState([]);

  useEffect(() => {
    if (apply_item.id === 0) return;
    let cancelLoading = false;
    if (!cancelLoading) {
      setCode(apply_item.code);
      setName(apply_item.name);
      setType(apply_item.type);
      setMessage(apply_item.message);
      setAmount(apply_item.amount);
      setAnnex(apply_item.annex);
      setDataLoaded(true);
    }

    return () => {
      cancelLoading = true;
    };
  }, [apply_item]);

  function handleCodeChange(event) {
    const value = trim(event.target.value);
    setCode(value);
    setIsValid(value !== "" && name !== "" );
  }

  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "" && code !== "" );
  }
  function handletypeChange(event) {
   // const value = trim(event.target.value);
    const value=event;
    setType(value);
    setIsValid(value !== "" && code !== "" );
    let itemvalues=[];
    let  classn="保洁协议";
    if(value==='xz')
    {
      itemvalues= [{
      value: "baojxy",
      label: "保洁协议",
    },
      {
        value: "feiyjsxy",
        label: "费用结算协议",
      },
      {
        value: "hhpjzbyx",
        label: "花卉盆景租摆协议",
      }];
    }else if(value ==='kj'){
      classn="frydfkzms";
      itemvalues= [{
      value: "frydfkzms",
      label: "法人用代付款证明（单次）",
    },
      {
        value: "frydfkzma",
        label: "法人用代付款证明（期限内全部结帐）",
      },
      {
        value: "zrrydfkzma",
        label: "自然人用代付款证明（期限内全部结帐）",
      }];
    }else if(value ==='rl'){
      classn="bmclh";
      itemvalues= [{
      value: "bmclh",
      label: "保密承诺函",
    },
      {
        value: "bmxy",
        label: "保密协议",
      },
      {
        value: "ldht",
        label: "劳动合同",
      }];
    }else if(value ==='wl'){
      classn="byfwht";
      itemvalues= [{
      value: "byfwht",
      label: "搬运服务合同",
    },
      {
        value: "cght",
        label: "采购合同",
      },
      {
        value: "glysht",
        label: "公路运输合同",
      }];
    }else if(value ==='xx'){
      classn="jsfwxyzbcxy";
      itemvalues= [{
      value: "jsfwxyzbcxy",
      label: "技术服务协议之补充协议",
    },
      {
        value: "rjcgxy",
        label: "软件采购协议",
      },
      {
        value: "sbzlxy",
        label: "设备租赁协议",
      }];
    }
    settypedetail(classn);
    setitemvalue(itemvalues);
  }
  function  party_aSelect(){

    return (
      <Select style={{ width: 600 }} value={party_a} onChange={handletypeChange}>
        {itemvalue.map(item => (
          <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
        ))}
      </Select>
    );
  };
  function unitSelectChange(event) {
    const value=event;
    setType(value);
    setIsValid(value !== "" && code !== "" );
  }
    function handlemessageChange(event) {
    const value = trim(event.target.value);
    setMessage(value);
    setIsValid(value !== "" && code !== "" );
  }
    function handleamountChange(event) {
    const value = trim(event.target.value);
    setAmount(value);
    setIsValid(value !== "" && code !== "" );
  }
    function handlesupplierChange(event) {
    const value = trim(event);
    setIsValid(value !== "" && code !== "" );
  }
   function handleChange(info) {
    let fileList = [...info.fileList];

    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    // fileList = fileList.slice(-2);

    // 2. Read from response and show file link
    fileList = fileList.map(file => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    setAnnex(fileList);
  };
   function handledown(file){
     let  filename=file.name;
     let AjaxUrl = 'api/upload/downloadfile/' +filename;
     fetch(AjaxUrl).then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            let filename = res.headers.get('Content-Disposition');
            if (filename) {
                filename = filename.match(/"(.*)"/)[1]; //提取文件名
                a.href = url;
                a.download = filename; //给下载下来的文件起个名字
                a.click();
                window.URL.revokeObjectURL(url);
                a = null;
            }
        }));
  };
   function getPdfURL(){
        // const _this = this;
        const props = {
            name: 'file',
            action: 'api/upload/uploadfile/contractapply/editor/0/0/'+apply_item.id,
            headers: {
                authorization: 'authorization-text',
            },
           onChange: handleChange,
           onDownload: handledown,
           onRemove(infos){
            let uid=infos.uid;
            const id=apply_item.id;
            Uploads.removefile({sourcetype: "contractapply",sourceid:id,uid:uid}).then(data => {
                 if(data.code==="sucess"){
                    notification.success(data.msg);
                 }
                 else{
                  notification.error(data.msg);
                  }
                }).catch(error => {
                  notification.error(get(error, "response.data.message", "删除失败."));
                });
           },
            showUploadList: {
            showDownloadIcon: true,
            downloadIcon: '下载',
            showRemoveIcon: true,
            removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
          },
        };
        return props;
    };
  function onChange(value) {
    console.log(value);
  }

  // Just show the latest item.
  function displayRender(label) {
    return label[label.length - 1];
  }
  function handleSubmit() {
    setSaveInProgress(true);

    // if (apply_item.id === 0) {
    //   OrgUnit.create({code: code, name: name, orgunit_enums: orgUnitEnums})
    //     .then(() => {
    //       dialog.close({ success: true});
    //     })
    //     .catch(error => {
    //       notification.error(error.message, error.detailedMessage);
    //       setSaveInProgress(false);
    //     });
    // } else {
    //   OrgUnit.save({id: orgunit_id, code: code, name: name, orgunit_enums: orgUnitEnums})
    //     .then(() => {
    //       dialog.close({ success: true});
    //     })
    //     .catch(error => {
    //       notification.error(error.message, error.detailedMessage);
    //       setSaveInProgress(false);
    //     });
    // }
  }

  return (
  //  const formLayout = {labelCol: { span: 4 }, wrapperCol: { span: 14 },};
    <Modal
      {...dialog.props}
      {...(isCreateApplyEnabled ? {} : { footer: null })}
      title="合同申请单"
      width={document.querySelector('body').offsetWidth*0.7}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateApplyDialogExtra" disabled={!isCreateApplyEnabled}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
         <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="申请日期">
            <DatePicker
              locale={locale}
              defaultValue={bill}
              onChange={handleNameChange}
              placeholder="申请日期"
              disabled={saveInProgress}
              autoFocus
            />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办人">
              <Select style={{ width:  300 }} defaultValue={employee} onChange={handletypeChange}>
                <Select.Option key="1" value='1'>张三</Select.Option>
                <Select.Option key="2" value='2'>李四</Select.Option>
              </Select>
            </Form.Item>
				  </Col>
        </Row>
      <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办部门">
              <Select style={{ width:  300 }} defaultValue={employee} onChange={handletypeChange}>
                <Select.Option key="1" value='1'>采购部</Select.Option>
                <Select.Option key="2" value='2'>生产部</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        	<Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同分类">
              <Cascader options={options} expandTrigger="hover" displayRender={displayRender} defaultValue={type}  onChange={onChange}/>
            </Form.Item>
          </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="编码">
              <Input
                defaultValue={code}
                onChange={handleCodeChange}
                placeholder="编码"
                disabled={saveInProgress}
                autoFocus
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="名称">
              <Input
                defaultValue={name}
                onChange={handleNameChange}
                placeholder="名称"
                disabled={saveInProgress}
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            {customerloaded && (
            <Form.Item style={{ marginBottom: 5 }} label="甲方">
              <Select style={{ width:  600 }}  loading={!customerloaded} defaultValue={party_a} onChange={handletypeChange}>
              {customer.map(item => (
                <Select.Option key={item.id} value={item.id}>{item.strcustomername}</Select.Option>
              ))}
            </Select>
            </Form.Item>
            )}
          </Col>
        </Row>
        <Row>
				  <Col span={10}>
            {customerloaded && (
            <Form.Item style={{ marginBottom: 5 }} label="乙方">
              <Select style={{ width:  600 }} loading={!customerloaded} defaultValue={party_b} onChange={handletypeChange}>
              {customer.map(item => (
                <Select.Option key={item.id} value={item.id}>{item.strcustomername}</Select.Option>
              ))}
            </Select>
            </Form.Item>
            )}
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            {customerloaded && (
            <Form.Item style={{ marginBottom: 5 }} label="其它关联方">
              <Select style={{ width:  600 }} loading={!customerloaded} defaultValue={party_c} onChange={handletypeChange}>
              {customer.map(item => (
                <Select.Option key={item.id} value={item.id}>{item.strcustomername}</Select.Option>
              ))}
            </Select>
            </Form.Item>
            )}
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="收付方向">
              <Select style={{ width:  300 }} defaultValue={pay_direction} onChange={handlesupplierChange} disabled={saveInProgress}>
                <Select.Option key="合同单位" value='合同单位'>合同单位</Select.Option>
                <Select.Option key="合同单位11" value='合同单位11'>合同单位11</Select.Option>
                <Select.Option key="合同单位22" value='合同单位22'>合同单位22</Select.Option>
              </Select>
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同签订日期">
            <DatePicker
              locale={locale}
              defaultValue={sign}
              onChange={handleNameChange}
              placeholder="合同签订日期"
              disabled={saveInProgress}
            />
            </Form.Item>
				  </Col>
        </Row>
         <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同开始日期">
            <DatePicker
              locale={locale}
              defaultValue={starts}
              onChange={handleNameChange}
              placeholder="合同开始日期"
              disabled={saveInProgress}

            />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同终止日期">
            <DatePicker
              locale={locale}
              defaultValue={ends}
              onChange={handleNameChange}
              placeholder="合同终止日期"
              disabled={saveInProgress}
            />
            </Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同金额(¥)">
              <Input
                defaultValue={amount}
                onChange={handleamountChange}
                placeholder="合同金额(¥)"
                disabled={saveInProgress}
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同金额(大写)">
              <Input
                defaultValue={amount_words}
                onChange={handleamountChange}
                placeholder="合同金额(大写)"
                disabled={saveInProgress}
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="记录事项">
              <textarea
                rows="5" cols="100"
                textAlignVertical="top"
                height="100px"
                defaultValue={message}
                onChange={handlemessageChange}
                placeholder="记录事项"
                disabled={saveInProgress}
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="附件">
              <Upload {...getPdfURL()} >
                <Button>
                  <UploadOutlined /> 上传
                </Button>
              </Upload>
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="状态">
               <Checkbox checked={bytstatus}>状态</Checkbox>
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateApplyDialog.propTypes = {
  apply_item: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateApplyDialog);
